#include <vector>
#include <utility>

using std::vector;

class Solution {
public:
    int maximalSquare(vector<vector<char>>& matrix) {
        int m = matrix.size();
        int n = matrix[0].size();
        vector<vector<int>> v;
        vector<int> tmp;
        for (int i = 0; i < m; i++) {
            tmp = vector<int>(n, 0);
            v.push_back(tmp);
        }
        for (int i = 0; i < m; i++) {
            v[i][0] = (matrix[i][0] == '1');
        }
        for (int i = 0; i < n; i++) {
            v[0][i] = (matrix[0][i] == '1');
        }
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                if (matrix[i][j] == '0') {
                    v[i][j] = 0;
                }
                else {
                    v[i][j] = std::min(v[i - 1][j - 1], std::min(v[i - 1][j], v[i][j - 1])) + 1;
                }
            }
        }
        int max = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (v[i][j] > max) {
                    max = v[i][j];
                }
            }
        }
        return max * max;
    }
};